package su.jiedai.service.impl;

import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.kuakao.core.base.util.SystemUtils;
import net.kuakao.core.exception.DataBaseException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

import su.jiedai.dao.IJiedaiDAO;
import su.jiedai.dto.JiedaiDto;
import su.jiedai.entity.JiedaiEntity;
import su.jiedai.service.IJiedaiService;

public class JiedaiService implements IJiedaiService {
	
	@Autowired
	private IJiedaiDAO jiedaiDAO;

	public List<JiedaiEntity> queryJiedaiByPage(JiedaiDto jiedaiDto, Model model) throws Exception {
		return jiedaiDAO.queryByPage(jiedaiDto);
	}
	
	public List<JiedaiEntity> getAll(String year) throws SQLException{
		List<JiedaiEntity> list = jiedaiDAO.getAll(year);
		if(list == null || list.isEmpty())return list;
		//设置余额
		double balance = 0;
		for(JiedaiEntity jd : list){
			if(jd.getJdDesc() != null && jd.getJdDesc().equals("上年结转")){
				balance = jd.getJdAmountJiezhuan();
			}else{
				balance = balance + jd.getJdAmountJie() - jd.getJdAmountDai();				
			}
			jd.setJdBalance(balance);
			//修改“余额方向”
			if(balance < 0){
				jd.setJdType(JiedaiDto.JIEDAI_TYPE_DAI);
			}else if(balance == 0){
				jd.setJdType(JiedaiDto.JIEDAI_TYPE_PING);
			}else{
				jd.setJdType(JiedaiDto.JIEDAI_TYPE_JIE);
			}
		}
		return list;
	}
	
	public List<Map<String,Object>> getCountList(String year) throws SQLException{
		List<JiedaiEntity> list = this.getAll(year);
		if(list==null || list.isEmpty())return null;
		List<Map<String,Object>> res = new ArrayList<Map<String,Object>>();
		double monthJieCount = 0,monthDaiCount = 0,yearJieCount = 0,yearDaiCount = 0;
		int totalMonth = getMonthOfDate(list.get(0).getJdDate());
		int m = 0;
		Map<String,Object> one;
		Map<String,Double> countInfo;
		for(JiedaiEntity jdEntity : list){
			m = getMonthOfDate(jdEntity.getJdDate());
			if(totalMonth != m){//更换月份
				//月合计信息
				one = new HashMap<String, Object>();
				countInfo = new HashMap<String, Double>();
				countInfo.put("monthNum", Double.valueOf(totalMonth+""));
				countInfo.put("jieCount", monthJieCount);
				countInfo.put("daiCount", monthDaiCount);
				one.put("monthCount", countInfo);
				res.add(one);
				//累计信息
				one = new HashMap<String, Object>();
				countInfo = new HashMap<String, Double>();
				countInfo.put("monthNum", Double.valueOf(totalMonth+""));
				countInfo.put("jieCount", yearJieCount);
				countInfo.put("daiCount", yearDaiCount);
				one.put("yearCount", countInfo);
				res.add(one);
				//月合计信息归零
				monthJieCount = 0;
				monthDaiCount = 0;
				totalMonth = m;
			}
			
			one = new HashMap<String, Object>();
			one.put("jdEntity", jdEntity);
			res.add(one);
			
			monthJieCount += jdEntity.getJdAmountJie();
			yearJieCount += jdEntity.getJdAmountJie();
			monthDaiCount += jdEntity.getJdAmountDai();
			yearDaiCount += jdEntity.getJdAmountDai();
		}
		//遍历结束后，统计最后一个月的数据
		//月合计信息
		one = new HashMap<String, Object>();
		countInfo = new HashMap<String, Double>();
		countInfo.put("monthNum", Double.valueOf(totalMonth+""));
		countInfo.put("jieCount", monthJieCount);
		countInfo.put("daiCount", monthDaiCount);
		one.put("monthCount", countInfo);
		res.add(one);
		//累计信息
		one = new HashMap<String, Object>();
		countInfo = new HashMap<String, Double>();
		countInfo.put("monthNum", Double.valueOf(totalMonth+""));
		countInfo.put("jieCount", yearJieCount);
		countInfo.put("daiCount", yearDaiCount);
		one.put("yearCount", countInfo);
		res.add(one);
		
		return res;
	}
	
	private int getMonthOfDate(Date date){
		int month = 0;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		month = cal.get(Calendar.MONTH) + 1;
		return month;
	}

	public JiedaiEntity getJiedaiById(int jdId) throws Exception {
			JiedaiEntity jiedaiEntity = null;
			if(jdId != 0) {
				jiedaiEntity = jiedaiDAO.getById(jdId);
			}
			return jiedaiEntity;
	}

	public void saveJiedai(JiedaiDto jiedaiDto, Model model) throws Exception {
		JiedaiEntity jiedaiEntity = jiedaiDto.toJiedaiEntity();
		jiedaiEntity.setJdStatus(JiedaiDto.JIEDAI_STATUS_ENABLE);
		if(jiedaiEntity.getId()==0){
			jiedaiEntity.setJdCreateTime(new Date());
			jiedaiDAO.insert(jiedaiEntity);
		}else{
			jiedaiDAO.update(jiedaiEntity);
		}
	}

	public void destroyJiedai(int jdId) throws Exception {
		if(jdId != 0) {
			jiedaiDAO.remove(jdId);
		}
	}
	
	public void operateExcelData(List<List<String[]>> list,PrintWriter out)throws DataBaseException{
		if(list==null || list.isEmpty()){
			out.println("没有有效数据，请确保excel文件版本是2003或更高");
			throw new DataBaseException();
		}
		int i = 1;
		int importRowNum = 0;
		JiedaiEntity jdEntity;
		String eDate="",eKey="",eDesc="",eCode="",eType="",jdAmountJie="",jdAmountDai="",jdAmountJiezhuan="";
		for(String[] row : list.get(0)){//第一个表单中的行
			i++;
			int cloNum = row.length;
			//test
//			out.println("colNum==="+cloNum);
//			for(int s=0;s<cloNum ; s++){
//				out.print(row[s]+"a==a");
//			}
//			out.println();
			//过滤
			eDesc = row[2];
			if(StringUtils.isBlank(eDesc)){
				out.println("第"+i+"行的摘要为空，请修改");
				throw new DataBaseException();
			}
			eDesc = eDesc.trim().replaceAll(" ", "").replaceAll(" ", "");
			if("本期合计".equals(eDesc) || "本年累计".equals(eDesc) || "期初余额".equals(eDesc) || "结转下年".equals(eDesc)){
				continue;
			}
			//验证
			eDate = row[0];
			if(StringUtils.isBlank(eDate)){
				out.println("第"+i+"行的日期为空，请修改");
				throw new DataBaseException();
			}
			eKey = row[1];
//			if(StringUtils.isBlank(eKey)){
//				out.println("第"+i+"行的凭证字号为空，请修改");
//				throw new DataBaseException();
//			}
			if(StringUtils.isBlank(row[6])){
				out.println("第"+i+"行的余额方向为空，请修改");
				throw new DataBaseException();
			}
			if("借".equals(row[6])){
				eType = String.valueOf(JiedaiDto.JIEDAI_TYPE_JIE);
			}
			if("货".equals(row[6])){
				eType = String.valueOf(JiedaiDto.JIEDAI_TYPE_DAI);
			}
			if("平".equals(row[6])){
				eType = String.valueOf(JiedaiDto.JIEDAI_TYPE_PING);
			}
			if(StringUtils.isBlank(eType) || Double.valueOf(eType)==0){
				out.println("第"+i+"行的余额方向不是借或货或平，请修改");
				throw new DataBaseException();
			}
			jdAmountJie = row[4];
			jdAmountDai = row[5];
			if(eDesc.equals("上年结转")){
				jdAmountJiezhuan = row[7];
			}
			if(StringUtils.isBlank(jdAmountJie) && StringUtils.isBlank(jdAmountDai) && StringUtils.isBlank(jdAmountJiezhuan)){
				out.println("第"+i+"行的借货金额为0，请修改");
				throw new DataBaseException();
			}
			
			jdEntity = new JiedaiEntity();
			jdEntity.setJdKey(eKey);
			jdEntity.setJdDesc(eDesc);
			jdEntity.setJdCode(eCode);
			try {
				jdEntity.setJdDate(SystemUtils.strToDate(eDate, "yyyy-MM-dd"));
				jdEntity.setJdAmountJie(SystemUtils.strToDouble(jdAmountJie));
				jdEntity.setJdAmountDai(SystemUtils.strToDouble(jdAmountDai));
				jdEntity.setJdAmountJiezhuan(SystemUtils.strToDouble(jdAmountJiezhuan));
				jdEntity.setJdType(SystemUtils.strToInt(eType));
			} catch (Exception e) {
				out.println("第"+i+"行数据异常，请修改");
				throw new DataBaseException();
			}
			
			jdEntity.setJdStatus(JiedaiDto.JIEDAI_STATUS_ENABLE);
			jdEntity.setJdCreateTime(new Date());
			try {
				jiedaiDAO.insert(jdEntity);
				importRowNum++;
			} catch (SQLException e) {
				out.println("第"+i+"行数据异常，请修改");
				throw new DataBaseException();
			}
		}
		out.println("成功导入 "+importRowNum+" 行数据，请到‘借货信息管理’页面刷新页面以查看新导入的数据");
	}

	public void removeAll() throws SQLException{
		jiedaiDAO.removeAll();
	}
}

